package tracker.ui;

import tracker.model._

trait SystemController {
  
  var system: TimeTrackingSystem = null 
  var current: Activity = null  
  
  def prompt(title: String): String
  def promptText(title: String): String
  def onStartProgress()
  def onStopProgress()
  
  def initialize() {
    dataDir.mkdirs
    system = new TimeTrackingSystem(userDataFile)
  }
  
  def dispose() {
    if (system != null) {
      flushCurrentActivity()
      system.dispose()
    }
  }
  
  import bamboo.io.Path._
  
  def userHome = System.getProperty("user.home")
  
  def dataDir = combine(userHome, ".tracker")
  
  def userDataFile = combine(dataDir, "time.db4o")
  
  def newProject() {
    val name = prompt("New Project")
    if (name != null) {
      system.addProject(new Project(name))
    }
  }
  
  def newTask(p: Project) {
    val name = prompt("New Task")
    if (name != null) {
      system.addTask(new Task(p, name))
    }
  }
  
  def startProgress(t: Task) = {
    flushCurrentActivity()
    startNewActivity(t)
  }
  
  def discardCurrent() = {
    if (current ne null) {
      system.discard(current)
      onStopProgress()
    }
  }
  
  def stopProgress() {
    val notes = promptText("Notes: ")
    if (notes ne null) {
      current.notes = notes
    }
    system.flush(current)
    current = null
    onStopProgress()
  }
  
  def flushCurrentActivity() {
    if (current == null) return
    system.flush(current)
  }
  
  private def startNewActivity(t: Task) {
    current = system.startProgress(t)
    onStartProgress()
  }

}
